/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package embeddedpaint.user_interface.tools;

import embeddedpaint.model.feature.AImageTool;
import embeddedpaint.model.layers.LayerImage;
import embeddedpaint.model.layers.LayerManager;
import embeddedpaint.user_interface.tools.dialog.chooser.MyFilechooserLoader;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ToolsLoadPicture extends AImageTool
{
    private static final String M_LABEL_TEXT                = "Load Picture";
    private static final String M_ICON_PATH                 = "images/open.png";
    private static final String M_DEFAULT_NEW_LAYER_NAME    = "New Layer ";
    private static final String M_ERROR_MESSAGE_LOAD_TEXT   = "Error during the image loading :\n";
    private static final String M_ERROR_MESSAGE_LOAD_TITLE  = "Loading error";

    public ToolsLoadPicture (LayerManager imageManager, JFrame application)
    {
        super(imageManager, application);
    }

    @Override
    public void actionPerformed (ActionEvent e)
    {
        String filePath = this.selectImage();

        if (filePath != null)
        {
            try
            {
                Image image = ImageIO.read(new File(filePath));

                LayerImage layer = new LayerImage(M_DEFAULT_NEW_LAYER_NAME + this.m_imageManager.getM_imageList().size());
                
                layer.setM_img   (image);
                layer.setM_height(image.getHeight(null));
                layer.setM_width (image.getWidth (null));

                this.m_imageManager.add(layer);
            }
            catch (IOException ex)
            {
                JOptionPane.showMessageDialog(m_application, M_ERROR_MESSAGE_LOAD_TEXT + ex, M_ERROR_MESSAGE_LOAD_TITLE, JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    @Override
    public String getLabel ()
    {
        return M_LABEL_TEXT;
    }

    @Override
    protected String getIconName ()
    {
        return M_ICON_PATH;
    }

    private String selectImage ()
    {
        JFileChooser fileChooser = new MyFilechooserLoader();

        fileChooser.showOpenDialog(this.m_application);

        if (fileChooser.getSelectedFile() != null)
        {
            return fileChooser.getSelectedFile().getPath();
        }

        return null;
    }
}
